<?php


namespace app\common\model;


use app\common\controller\FileController;

class UploadFile extends BaseModel
{
    /**
     * 上传多图
     * @return mixed
     */
    public function uploadMore(){
        $image= $this->upload(request()->userId,'file');
       if(is_array($image)){
           for ($i = 0; $i< count($image);$i++){

               $image[$i]['file'] = getFileUrl($image[$i]['file']);
           }
       }
        return $image;
    }

    /**
     * 上传图片
     * @param string $userid
     * @param string $field
     * @return \think\Collection
     * @throws \Exception
     */
    public function upload($userid="",$field=""){
        //获取图片
        $files = request()->file($field);
        if(is_array($files)){
            //多图上传
            $arr = [];
            foreach ($files as $file){
                $res = FileController::UploadEvent($file);
                if($res['status']){
                    $arr[] = [
                        'url' => $res['data'],
                        'user_id' => $userid
                    ];
                }
            }
            return $this->saveAll($arr);
        }
        //单图上传
        if(!$files) TApiException('请选择要上传的图片',10000,200);
        //单文件上传
        $file = FileController::UploadEvent($files);
        //上传失败
        if(!$file['status']) TApiException($file['data'],10000,200);

        //上传成功写入数据库
        return self::create([
           'url' => $file['data'],
           'user_id' => $userid
        ]);
    }


}